package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.pojo.Unit;
import com.intelligent.service.UnitService;
import com.intelligent.mapper.UnitMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

/**
* @author lenovo
* @description 针对表【unit(单位信息表)】的数据库操作Service实现
* @createDate 2025-08-27 15:58:27
*/
@Service
public class UnitServiceImpl extends ServiceImpl<UnitMapper, Unit>
    implements UnitService{

	@Resource
	private UnitMapper unitMapper;

	@Override
	public IPage<Unit> pageUnit(Page<Unit> page, String unitCode, String unitName, Integer status) {
		return unitMapper.pageUnit(page, unitCode, unitName, status);
	}

	@Override
	public boolean createUnit(Unit unit) {
		if (unit == null) {
			return false;
		}
		if (unit.getUnitCode() == null || unit.getUnitCode().trim().isEmpty()) {
			unit.setUnitCode(generateUnitCode());
		}
		int affected = unitMapper.insertUnit(unit);
		return affected > 0;
	}

	@Override
	public boolean updateUnit(Unit unit) {
		if (unit == null || unit.getUnitId() == null) {
			return false;
		}
		int affected = unitMapper.updateUnit(unit);
		return affected > 0;
	}

	@Override
	public boolean deleteUnit(Long unitId) {
		if (unitId == null) {
			return false;
		}
		int affected = unitMapper.deleteUnit(unitId);
		return affected > 0;
	}

	@Override
	public Unit selectUnitById(Long unitId) {
		if (unitId == null) {
			return null;
		}
		return unitMapper.selectUnitById(unitId);
	}

	private String generateUnitCode() {
		String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
		int rand = ThreadLocalRandom.current().nextInt(0, 1000);
		return "U" + timestamp + String.format("%03d", rand);
	}
}




